import { MaybeRef, UnwrapNestedRefs } from "vue";
import { useApiFetch, type ApiResponse } from "./useApiFetch";
import { toUrlParams } from "@/components/utils";
export function usePageFetch<T = any>(
  url: MaybeRef<string>,
  {
    page = 1,
    pageSize = 10,
    params = {},
  }: {
    page?: MaybeRef<number>;
    pageSize?: MaybeRef<number>;
    params?: UnwrapNestedRefs<object>;
  },
) {
  const total = ref(0),
    _page = toRef(page),
    _pageSize = toRef(pageSize);

  const result = useApiFetch(
    computed(
      () =>
        `${toRef(url).value}?${toUrlParams({
          ...params,
          limit: _pageSize.value,
          offset: (_page.value - 1) * _pageSize.value,
        })}`,
    ),
    { refetch: true },
  ).json<ApiResponse<T>>();
  watch(result.data, (val) => {
    if (val?.success) {
      total.value = val.query.count;
    }
  });
  return {
    ...result,
    total,
    page: _page,
    pageSize: _pageSize,
  };
}
